from pyecharts import options as opts
from pyecharts.charts import WordCloud, Pie, Line, Radar
import pandas as pd

# 假设已通过Spark分析得到以下结果（示例数据）
behavior_distribution = [("点击", 42000), ("加购", 5000), ("收藏", 2000), ("购买", 1000)]  # 行为类型分布
category_clicks = [("服装", 12000), ("家电", 8000), ("美妆", 7500), ("食品", 6000)]  # 商品类别点击量
hour_active = [(8, 1200), (9, 1500), (10, 1800), (11, 2000)]  # 小时级活跃用户数
user_radar = [{"name": "用户A", "value": [80, 90, 70, 60]}]  # 雷达图数据（活跃度、消费力等维度）]

# 词云图：商品类别点击量
def wordcloud_chart() -> WordCloud:
    c = (
        WordCloud()
        .add(series_name="商品类别点击量", data_pair=category_clicks, word_size_range=[20, 100])
        .set_global_opts(title_opts=opts.TitleOpts(title="商品类别点击量词云"))
    )
    return c

# 饼状图：行为类型分布
def pie_chart() -> Pie:
    c = (
        Pie()
        .add("行为类型", behavior_distribution)
        .set_global_opts(title_opts=opts.TitleOpts(title="用户行为类型分布"))
        .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}次 ({d}%)"))
    )
    return c

# 折线图：小时级活跃用户数
def line_chart() -> Line:
    x_data = [str(hour) for hour, _ in hour_active]
    y_data = [count for _, count in hour_active]
    c = (
        Line()
        .add_xaxis(x_data)
        .add_yaxis("活跃用户数", y_data)
        .set_global_opts(
            title_opts=opts.TitleOpts(title="小时级用户活跃趋势"),
            xaxis_opts=opts.AxisOpts(name="小时"),
            yaxis_opts=opts.AxisOpts(name="用户数")
        )
    )
    return c

# 雷达图：用户多维度分析
def radar_chart() -> Radar:
    c = (
        Radar()
        .add_schema(
            schema=[
                opts.RadarIndicatorItem(name="活跃度", max_=100),
                opts.RadarIndicatorItem(name="消费力", max_=100),
                opts.RadarIndicatorItem(name="加购率", max_=100),
                opts.RadarIndicatorItem(name="复购率", max_=100)
            ]
        )
        .add("用户画像", [user['value'] for user in user_radar])
        .set_global_opts(title_opts=opts.TitleOpts(title="用户多维度分析雷达图"))
    )
    return c

# 生成所有图表
if __name__ == "__main__":
    wordcloud_chart().render("商品类别词云.html")
    pie_chart().render("行为类型分布.html")
    line_chart().render("小时活跃趋势.html")
    radar_chart().render("用户画像雷达图.html")
